<template>
  <div class="sim_view">
    <el-dialog title="单据打印" :visible.sync="dialogVisible" lock-scroll width="550px" destroy-on-close>
      <div style="display: flex; align-items: center">
        <span>打印模板</span>
        <el-select v-model="templateId" style="margin: 0 20px; width: 240px" filterable @change="templateChange()">
          <el-option v-for="item in templateOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
        <a @click="toTemplateSetting('edit')" :disabled="!printPermissions">设置模板</a>
        <a @click="toTemplateSetting('add')" :disabled="!printPermissions" style="margin-left: 20px">新增模板</a>
      </div>
      <div style="margin: 20px 0">
        <span style="margin-right: 20px">打印设置</span>
        <el-checkbox v-model="checked" @change="handlePrintTimeChange">显示打印时间</el-checkbox>
      </div>
      <div style="display: none" id="barCodeView" class="dialog_div">
        <printSettlement id="printMe" :baseData="styleData" v-if="showPrint"></printSettlement>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" v-print="'#printMe'" @click="addPrintRecord" :disabled="styleData.length == 0"
          >保存</el-button
        >
        <el-button @click="printPreview" :disabled="styleData.length == 0">预览</el-button>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
    <el-dialog title="预览" :visible.sync="previewVisible" width="950px" v-if="showPrint">
      <div :style="{ width: 1103 * 0.8 + 'px', height: 774 * 0.8 + 'px' }" style="overflow: hidden; overflow-y: scroll">
        <div style="width: 100%">
          <printSettlement id="printDom" :baseData="styleData"></printSettlement>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import printSettlement from '@/components/c_print/printSettlement'
import { getAction, postAction, putAction, downPostFile } from '@/api/manage'
import {
  handlePermissions,
  handleOtherPerms,
  sysConfig,
  getSystemParamsByName,
  formatMoney,
  formatPrice,
  formatNumber,
  delcommafy,
  handleArrayToObject,
  handleObjectToArray,
  formatHundredMillionPrice,
} from '@/utils/index'
export default {
  props: {
    tipsData: Object,
  },
  components: {
    printSettlement,
  },
  data() {
    return {
      dialogVisible: false,
      styleData: [],
      templateOptions: [],
      templateId: '',
      billData: {},
      showPrint: false,
      printPermissions: false, //打印模板设置权限
      checked: false,
      previewVisible: false,
      billName: '',
    }
  },
  mounted() {
    window.addEventListener('mousedown', this.getPrintTime)
  },
  created() {
    this.printPermissions = handleOtherPerms('打印模板设置')
  },
  methods: {
    getPrintTime() {
      if (this.styleData.length > 0) {
        let date = this.$dateUtil.formatDateHMS(new Date())
        this.styleData[0].printTime = date
      }
    },
    getTemplateList(billName) {
      getAction('/xghprinttemplate/xghPrintTemplate/list', { orderType: billName }).then((res) => {
        if (res.success) {
          this.templateOptions = res.result
          // 增加延时，避免默认的模板id匹配不到模板名称
          setTimeout(() => {
            // 设置默认选择模版
            this.templateOptions.forEach((item, index) => {
              if (index === 0) {
                this.templateId = item.id
              }
              if (item.isDefault == 1) {
                this.templateId = item.id
              }
            })
            if (this.templateId) {
              this.templateChange()
            }
          }, 100);
        } else {
          this.$elMessage.error(res.message)
        }
      })
    },
    onConfirm() {
      this.dialogVisible = !this.dialogVisible
      this.$emit('onConfirm', this.tipsData.tipsMark)
    },
    printPreview() {
      let date = this.$dateUtil.formatDateHMS(new Date())
      this.styleData[0].printTime = date
      setTimeout(() => {
        this.previewVisible = true
      }, 500)
    },
    show(data1, columnData, billName) {
      Object.assign(this.$data, this.$options.data())
      this.printPermissions = handleOtherPerms('打印模板设置')
      this.billName = billName
      this.getTemplateList(billName)
      this.dialogVisible = true

      let data = JSON.parse(JSON.stringify(data1))

      // 处理数据保留小数位数
      data.infoTableData.forEach((item) => {
        for (const key in item) {
          if (key.toLowerCase().includes('price')) {
            item[key] = this.$formatMoney(item[key])
          }
        }
      })
      this.billData = data
    },
    hide() {
      this.dialogVisible = false
    },
    sure() {
      this.$emit('onSure')
      this.hide()
    },
    getItemById(id) {
      for (let index = 0; index < this.templateOptions.length; index++) {
        const element = this.templateOptions[index]
        if (element.id == id) {
          return element
        }
      }
    },
    handlePrintTimeChange(val) {
      this.styleData[0].showPrintTime = val
    },
    templateChange() {
      let item = this.getItemById(this.templateId)
      console.log('item', item)
      let parse = JSON.parse(item.value)
      console.log('parse', parse)
      this.styleData = parse
      let data = this.billData
      // 打印时间
      this.styleData[0].showPrintTime = this.checked
      //单据头部5、明细6、尾部7
      this.styleData[4].otherData = data
      if (['付款结算单', '收款结算单', '物流代收结算单', '物流代付结算单', '物流运费结算单',].includes(item.orderType)) {
        this.styleData[5].topTableData = data.paymentTableData.map((item, index) => {
          item.idx = index + 1
          return item
        })
      }
      // this.styleData[5].topTableData.push({idx:'结销明细'})
      this.styleData[5].tableData = data.infoTableData.map((item, index) => {
        item.idx = index + 1
        return item
      })
      this.styleData[6].otherData = data

      console.log(this.styleData)

      this.showPrint = true
    },
    // 记录打印次数
    addPrintRecord() {
      let paramVal = {
        orderId: this.billData.id,
      }
      postAction('xghuserorderprintrecord/xghUserOrderPrintRecord/add', paramVal).then((res) => {
        if (res.code == 200) {
        }
      })
    },
    savePrint() {
      let date = this.$dateUtil.formatDateHMS(new Date())
      this.styleData[0].printTime = date
      this.addPrintRecord()
      // setTimeout(() => {
      //   this.jsPrintAction()
      // }, 500);

      // let old = document.body.innerHTML
      // let newstr = document.getElementById('printDom').innerHTML
      // document.body.innerHTML = newstr;
      // window.print()
      // document.body.innerHTML = old;
      // window.location.reload()
    },
    toTemplateSetting(type) {
      this.dialogVisible = false
      this.$router.push({
        name: 'baseInfomation-printSetting-printSetSettlement',
        params: {
          val: this.billName,
          type,
          tlId: type == 'edit' ? this.templateId || '' : '',
        },
      })
    },
    jsPrintAction() {
      console.log(document.getElementById('barCodeView'))
      let printWindow = window.open(
        '',
        '页面打印',
        'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=yes, copyhistory=no'
      )
      const el = document.getElementById('barCodeView').innerHTML
      printWindow.document.write(el)
      printWindow.focus()
      printWindow.print()
      printWindow.close()
    },
  },
}
</script>

<style lang="scss" scoped>
.sim_view {
  ::v-deep .el-dialog {
    .el-dialog__body {
      padding: 30px 30px 10px;
      // padding-bottom: 10px;
    }
  }
}
.codeDiv {
  display: flex;
  padding: 30px 0;
  align-items: center;
  border-bottom: 1px solid #eee;
}
.input {
  flex: 1;
  border: 1px solid #ebeef5;
  height: 40px;
  padding: 0 10px;
  border-radius: 5px;
}
.input:focus {
  outline: 1px solid #1890ff;
}
.dialog-footer {
  display: flex;
  justify-content: center;
  ::v-deep .el-button {
    width: 60px;
    height: 30px;
    margin: 0 15px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.dialog_div {
  width: 1103px;
  height: 754px;
}
::v-deep .el-select {
  height: 30px;
  width: auto;
  box-sizing: border-box;
  // margin-right: 6px;

  .el-input {
    height: 100%;

    .el-input__inner {
      width: 100%;
      height: 100%;
      font-size: 12px;
      padding: 0 12px 0 5px;
      .el-input__suffix-inner {
        height: 100%;
      }
    }

    .el-input__suffix {
      height: 100%;
      width: 20px;
      display: flex;
      align-items: center;
    }
  }
}
</style>